package SaveServlet.manager;

import com.lyq.bean.mySql.ElectC_Sql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/checkAssignStatus")
public class CheckAssignStatusServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private ElectC_Sql electC_Sql;

    @Override
    public void init() throws ServletException {
        // 初始化服务类
        electC_Sql = new ElectC_Sql();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();

        try {
            // 获取课程编号
            String courseId = request.getParameter("courseId");
            if (courseId == null || courseId.trim().isEmpty()) {
                out.print("{\"success\": false, \"message\": \"课程编号不能为空\", \"assigned\": false}");
                return;
            }

            // 获取筛选条件（专业和届数）
            String majorId = request.getParameter("majorId");
            String yearId = request.getParameter("yearId");

            // 如果请求中没有直接传递，尝试从session或之前保存的参数中获取
            HttpSession session = request.getSession();
            if (majorId == null) {
                majorId = (String) session.getAttribute("currentMajorId");
            }
            if (yearId == null) {
                yearId = (String) session.getAttribute("currentYearId");
            }

            // 检查课程分配状态
            boolean isAssigned = electC_Sql.isCourseAssigned(courseId);

            // 返回JSON结果
            out.print("{\"success\": true, \"assigned\": " + isAssigned + "}");

        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"系统错误: " + e.getMessage() + "\", \"assigned\": false}");
        }
    }
}